package com.hmall.item.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.item.client.ItemClient;
import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 虎哥
 */
@Service
@RequiredArgsConstructor
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    private final ItemClient itemClient;

    private final RestTemplate restTemplate;

    //SpringCloud规定的统一接口
    private final DiscoveryClient discoveryClient;

    @Override
    public void deductStock(List<OrderDetailDTO> items) {
        String sqlStatement = "com.hmall.mapper.ItemMapper.updateStock";
        boolean r = false;
        try {
            r = executeBatch(items, (sqlSession, entity) -> sqlSession.update(sqlStatement, entity));
        } catch (Exception e) {
            throw new BizIllegalException("更新库存异常，可能是库存不足!", e);
        }
        if (!r) {
            throw new BizIllegalException("库存不足！");
        }
    }

    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }


    @Override
    public void testNacos(List<Item> vo/*仅作为演示用*/) {
//        Nacos中注册过的服务名字(也就是Springboot中配置文件中定义的)
        List<ServiceInstance> instances = discoveryClient.getInstances("hm-service");
        if (CollUtil.isEmpty(instances)) {
            return;
        }
        ServiceInstance serviceInstance = instances.get(RandomUtil.randomInt(instances.size()));
        //serviceInstance.getHost()  可以取出各种信息
        ResponseEntity<List<ItemDTO>> responseEntity = restTemplate.exchange(
                serviceInstance.getUri() + "/items?id={ids}",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ItemDTO>>() {
                },
                CollUtil.join(vo, ",")
        );
    }

    @Override
    public void testNacosUp(List<Item> vo) {
        Set<Long> itemIds = vo.stream().map(Item::getId).collect(Collectors.toSet());
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (CollUtil.isEmpty(items)) {
            return;
        }
    }

}
